﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PSE.Updater.Common.Gateway.DataContract;
using PSE.Updater.Common.Providers;
using PSE.Updater.Client.Engine;
using PSE.Updater.Common;
using PSE.Framework.ErrorLogging;
using System.IO;

namespace PSE.Updater.Client.Providers.ConfigurationFile
{
    public class Update : UpdateBase
    {
        public Update() : base(ProviderType.ConfigurationFile) { }

        protected override void ShowUpdates(List<ModuleUpdatePackage> modules)
        {
            IList<DownloadedFile> updates = BeginDownload(modules);
            InstallConfiguration(updates, this.InstalledSystems);
        }

        private void ShowInformations(IList<DownloadedFile> files)
        {
            this.ShowSytrayIcon("BM&FBOVESPA", "Atualizações disponíveis. Clique aqui para ver os detalhes",
                () =>
                {
                    UI.Default finalizar = new UI.Default();
                    finalizar.Screen = PSE.Updater.Client.UI.Default.ScreenType.Finalize;
                    finalizar.ModulesUpdatePackage = from m in files 
                                                     select m.ModuleUpdatePackage;

                    finalizar.OnFinalizeClick = () => finalizar.Close();
                    finalizar.Show();
                });
        }

        private void InstallConfiguration(IList<DownloadedFile> downloadedFiles, IList<SystemInformation> installedSystems)
        {
            string bkpFile = string.Empty;
            var valids = from d in downloadedFiles
                         where d.ModuleUpdatePackage.Status != PackageStatus.Invalid 
                            && d.ModuleUpdatePackage.Status != PackageStatus.Missing
                         select d;

            foreach (DownloadedFile downloadedFile in valids)
            {
                try
                {
                    SystemInformation systemInformation = installedSystems.FirstOrDefault(i => i.SystemDetails.SystemName.Equals(downloadedFile.ModuleUpdatePackage.SystemName, StringComparison.CurrentCultureIgnoreCase));
                    if (systemInformation != null)
                    {
                        string config = systemInformation.SystemDetails.ConfigFiles.FirstOrDefault(c => c.EndsWith(downloadedFile.ModuleUpdatePackage.ModuleName, StringComparison.CurrentCultureIgnoreCase));
                        bkpFile = RenameFile(config);

                        if (File.Exists(downloadedFile.Path))
                        {
                            File.Move(downloadedFile.Path, config);
                            File.Delete(bkpFile);
                            downloadedFile.ModuleUpdatePackage.Status = PackageStatus.Installed;
                        }
                        else
                        {
                            //ErrorLogger.WriteLog(LogType.Error, ex);
                            downloadedFile.ModuleUpdatePackage.Status = PackageStatus.Missing;
                        }
                    }
                }
                catch (Exception ex)
                {
                    ErrorLogger.WriteLog(LogType.Error, ex);
                }
            }
            ShowInformations(downloadedFiles);
        }

        private string RenameFile(string file)
        {
            string newFile = file + ".bkp";
            try
            {
                File.Copy(file, newFile);
                File.Delete(file);
                return newFile;
            }
            catch
            {
                return file;
            }
        }
        protected override List<ModuleUpdatePackage> GetAvailableUpdates(SystemInformation system)
        {
            List<ModuleUpdatePackage> avaliableModules = null;
            try
            {
                List<ModuleVersion> modules = new List<ModuleVersion>();
                foreach (string config in system.SystemDetails.ConfigFiles)
                {
                    System.IO.FileInfo fileInfo = new System.IO.FileInfo(config);
                    string moduleName = fileInfo.Name;
                    //string moduleName = config.Replace(system.Path, "");
                    string version = System.IO.File.GetLastWriteTime(config).ToString();
                    
                    modules.Add(new ModuleVersion
                    {
                        ModuleName = moduleName,
                        Version = version,
                        SystemName = system.SystemName
                    });
                }
                avaliableModules = Service.Proxy.Instance.GetAvailableUpdates(ProviderType.ConfigurationFile, modules);
            }
            catch (Exception ex)
            {
                ErrorLogger.WriteLog(LogType.Error, ex);
                return null;
            }

            return avaliableModules;
        }

        protected override void DownloadProgressChanged(ModuleUpdatePackage pkg, int progress)
        {
            //TODO
        }
    }
}